<?php defined("MAIN_DIR") or die("No direct access");

$error = array();
if (isset($_GET['act']) && $_GET['act'] == "search") {
	
	$deposit_query = 
	"select `D`.*,`B`.`link`,`B`.`name` as `bank_name`,MAX(`DP`.`percent`) as `percent`
	from `deposit` as `D`,`bank` as `B`,`deposit_percent` as `DP`
	where
		`D`.`bank_id` = `B`.`bank_id` and `DP`.`deposit_id` = `D`.`deposit_id` and 
		(
			(`D`.`regionally` = '1' and
				(
					`B`.`bank_id` in (select `parent` from `bank` where `city_id` = '$_SESSION[city]' and `parent` != '0' ) or
					`B`.`bank_id` in (select `bank_id` from `bank` where `city_id` = '$_SESSION[city]' and `parent` = '0' )
				)
			) or
			(`B`.`city_id` = '$_SESSION[city]' and `D`.`regionally` = '0')
		)";
	
	if (isset($_GET['currency']) && $_GET['currency'] != "" && count($error) == 0) {
		$cur = trim(strip_tags($_GET['currency']));
		switch ($cur) {
			
			case "rub": $deposit_query .= " and `DP`.`currency` = 'RUB'"; break;
			case "usd": $deposit_query .= " and `DP`.`currency` = 'USD'"; break;
			case "euro": $deposit_query .= " and `DP`.`currency` = 'EUR'"; break;
			default: $error['currency'] = 1;
		}
	} else {
		$error['currency'] = 1;
	}
	
	if (isset($_GET['sum']) && $_GET['sum'] != "" && count($error) == 0) {
		$sum = trim(strip_tags($_GET['sum']));
		if (is_numeric($sum)) {
			$deposit_query .= " and `DP`.`amount` <= '$sum'";
		}
	}
	
	if (isset($_GET['period']) && $_GET['period'] != "" && count($error) == 0) {
		$period = explode("-",trim(strip_tags($_GET['period'])));
		
		if (count($period) == 2) {
			$deposit_query .= " and `DP`.`period` between '$period[0]' and '$period[1]'";
		} elseif (count($period) == 1) {
			$deposit_query .= " and `DP`.`period` >= '$period[0]'";
		}
	}
	
	$deposit_query .= " group by `DP`.`deposit_id`";
	
	if (isset($_GET['sort']) && $_GET['sort'] != "" && isset($_GET['ord']) && $_GET['ord'] != "" && count($error) == 0) {
		$sort = trim(strip_tags($_GET['sort']));
		$ord = trim(strip_tags($_GET['ord']));
		switch ($sort) {
			
			case "percent": $deposit_query .= ($ord == "desc") ? " order by `percent` desc" : " order by `percent` asc"; break;
		}
	}
	
	if (count($error) == 0) {
		$limit = 20;
		$deposit_res = mysql_query($deposit_query);
		$count = mysql_num_rows($deposit_res);
		$page = 1;
		if (isset($_GET['page']))
			$page = $_GET['page'];
		$max_page = ceil($count/$limit);
		if ($max_page == 0)
			$max_page++;
		if ($page > $max_page)
			$page = $max_page;
		elseif ($page < 1)
			$page = 1;
		$start_list = (ceil($page)-1)*$limit;
		$deposit_query .= " limit $start_list,$limit";
		$deposit_res = mysql_query($deposit_query);
		$deposit_count = mysql_num_rows($deposit_res);
	}
}

$head_title = "Вклады в ".$current_city['city_name_pred'];
$head_description = "Поиск по вкладам в банках ".$current_city['city_name_rod'];
$head_keywords = "вклад ".$current_city['city_name'];

if (isset($_GET['currency']) && $_GET['currency'] != "")
{
	$cur = trim(strip_tags($_GET['currency']));
	switch ($cur)
	{
		case "rub": $head_title = "Вклады в рублях в ".$current_city['city_name_pred'];
					$head_description = "Поиск по рублевым вкладам в банках ".$current_city['city_name_rod'];
					$head_keywords = "вклад рубли ".$current_city['city_name'];
					break;
		case "usd": $head_title = "Вклады в долларах в ".$current_city['city_name_pred'];
					$head_description = "Поиск по долларовым вкладам в банках ".$current_city['city_name_rod'];
					$head_keywords = "вклад доллары ".$current_city['city_name'];
					break;
		case "euro":$head_title = "Вклады в евро в ".$current_city['city_name_pred'];
					$head_description = "Поиск по вкладам в евро в банках ".$current_city['city_name_rod'];
					$head_keywords = "вклад евро ".$current_city['city_name'];
					break;
	}
}

require_once APP.HEADFILE;
?>
<script type="text/javascript" src="/files/js/bank_list.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("#type").change(function(){
		if ($(this).val() != 0)
			$("#errors > #type_er").remove();
	})
	$("#currency").change(function(){
		if ($(this).val() != 0)
			$("#errors > #currency_er").remove();
	})
})
function check_form()
{
	var value = true;
	$("#errors").html("");
	if ($("#type").val() == 0)
	{
		$("#errors").append("<span id='type_er'>Необходимо выбрать тип кредита<br /></span>");
		value = false;
	}
	if ($("#currency").val() == 0)
	{
		$("#errors").append("<span id='currency_er'>Необходимо выбрать валюту<br /></span>");
		value = false;
	}
	
	return value;
}
</script>
<h1>Вклады в <?php echo $current_city['city_name_pred']; ?></h1>
<div class="credity_1col">
	<form method="GET" onsubmit="return check_form()">
	<input type='hidden' name='act' value='search' />
	<table width="301" border="0" cellspacing="0" cellpadding="0">
		<tr>
			<td width="39%" align="left" class="golosovanie_form">Город</td>
			<td width="61%" align="left" class="golosovanie_form"><strong><?php echo $current_city['city_name']; ?></strong></td>
		</tr>
		<tr>
			<td align="left" class="golosovanie_form">Валюта</td>
			<td align="left" class="golosovanie_form">
				<select name="currency" id="currency" class="golosovanie_forma">
					<option value="rub"<?php
					if (isset($_GET['currency']) && $_GET['currency'] == "rub")
						echo " selected";
					?>>Рубли</option>
					<option value="usd"<?php
					if (isset($_GET['currency']) && $_GET['currency'] == "usd")
						echo " selected";
					?>>Доллары</option>
					<option value="euro"<?php
					if (isset($_GET['currency']) && $_GET['currency'] == "euro")
						echo " selected";
					?>>Евро</option>
				</select>
			</td>
		</tr>
		<tr>
			<td align="left" class="golosovanie_form">Сумма</td>
			<td align="left" class="golosovanie_form">
				<input name="sum" type="text" class="golosovanie_forma_text" <?php
				if (isset($_GET['sum']))
					echo " value='$_GET[sum]'";
				?>/>
			</td>
		</tr>
		<tr>
			<td align="left" class="golosovanie_form">Срок</td>
			<td align="left" class="golosovanie_form">
				<label for="textfield"></label>
				<select name="period" class="golosovanie_forma">
					<option value="0-3"<?php
					if (isset($_GET['period']) && $_GET['period'] == "0-3")
						echo " selected";
					?>>3 месяца</option>
					<option value="3-6"<?php
					if (isset($_GET['period']) && $_GET['period'] == "3-6")
						echo " selected";
					?>>6 месяцев</option>
					<option value="6-12"<?php
					if (isset($_GET['period']) && $_GET['period'] == "6-12")
						echo " selected";
					?>>1 год</option>
					<option value="12-36"<?php
					if (isset($_GET['period']) && $_GET['period'] == "12-36")
						echo " selected";
					?>>3 года</option>
					<option value="36-60"<?php
					if (isset($_GET['period']) && $_GET['period'] == "36-60")
						echo " selected";
					?>>5 лет</option>
					<option value="60-120"<?php
					if (isset($_GET['period']) && $_GET['period'] == "60-120")
						echo " selected";
					?>>10 лет</option>
					<option value="120-240"<?php
					if (isset($_GET['period']) && $_GET['period'] == "120")
						echo " selected";
					?>>20 лет и более</option>
				</select>
			</td>
		</tr>
		<tr>
			<td colspan="2" align="left" class="golosovanie_form"><div class="golosovanie_line"></div></td>
		</tr>
		<tr>
			<td align="left">&nbsp;</td>
			<td align="right" valign="top">
				<input type="submit" class="golosovanie_forma" id="button" value="Найти" />
			</td>
		</tr>
	</table>
	</form>
	<p id="errors" style="color:red"><?php
	if (count($error) > 0)
	{
		if (isset($error['currency']))
			echo "<span id='currency_er'>Необходимо выбрать валюту<br /></span>";
	}
	?></p>
</div><?php
if (!isset($_GET['act']))
{
	$max_query = "select `D`.`deposit_id`,`D`.`name`,`B`.`link`,`B`.`name` as `bank_name`,MAX(`DP`.`percent`) as `percent` from `deposit` as `D`,`bank` as `B`, `deposit_percent` as `DP` where `D`.`bank_id` = `B`.`bank_id` and `D`.`deposit_id` = `DP`.`deposit_id` and (
		(`B`.`city_id` = '$_SESSION[city]' and `B`.`parent` <> '0') or (`B`.`parent` = '0')
	)
	group by `D`.`deposit_id` order by `percent` desc limit 4";
	$max_res = mysql_query($max_query);
	if (mysql_num_rows($max_res) > 0)
	{
		?><div class="credity_2col" id="credity_min">
			<strong>Максимальные проценты</strong><?php
		while ($max_row = mysql_fetch_array($max_res))
		{
			?><div class="credity_min_heading">
					Вклад <a href="<?php echo "/$c_name";?>/deposits/<?php echo $max_row['deposit_id']; ?>" class="credity_blue_link"><strong><?php echo $max_row['name']; ?></strong></a>
					в банке «<a href="<?php echo "/$c_name";?>/banks/<?php echo $max_row['link'].".html"; ?>" class="credity_green_link"><strong><?php echo $max_row['bank_name']; ?></strong></a>»
				</div>
				<div class="credity_min_percent"><?php echo "до ".number_format($max_row['percent'],2)." %"?></div>
			<?php
		}
		?></div><?php
	}
}
?><div style="clear:both"></div><?php
if (isset($_GET['act']) && $_GET['act'] == "search" && count($error) == 0)
{
	$url = parse_url($_SERVER['REQUEST_URI']);
	if (isset($url['query']))
		$url_q = explode("&",$url['query']);
	
	$tmp = array();
	for ($z=0; $z<count($url_q); $z++)
		if ((strpos($url_q[$z],"sort=") === false) && (strpos($url_q[$z],"ord=") === false) && ($url_q[$z] != ""))
			$tmp[] = $url_q[$z];
	$link = "?".implode("&",$tmp)."&sort=";
	?><div id="kredity_result">
		<div class="kredity_result_heading">Результаты поиска</div><?php
		if ($count > 0)
		{
			?><table width="100%" border="0" cellspacing="0" cellpadding="8">
				<tr>
					<td width="19%" align="left" bgcolor="#FFFFFF"><strong>Банк</strong></td>
					<td width="30%" align="left" bgcolor="#FFFFFF"><strong>Название</strong></td>
					<td width="13%" align="left" bgcolor="#FFFFFF"><strong>Процент</strong></td>
				</tr>
				<tr>
					<td align="left">&nbsp;</td>
					<td align="left">&nbsp;</td>
					<td align="left">
						<a href="<?php echo $link."percent&ord=asc";?>"><img src="/files/images/arr_table_top.png" width="7" height="7" border="0" /></a>
						<a href="<?php echo $link."percent&ord=desc";?>"><img src="/files/images/arr_table_bottom.png" alt="" border="0" /></a>
					</td>
				</tr><?php
				while ($deposit_row = mysql_fetch_array($deposit_res))
				{
					?><tr>
						<td align="left"><a href="<?php echo "/$c_name";?>/banks/<?php echo $deposit_row['link'].".html"; ?>" class="credity_green_link"><?php
							echo $deposit_row['bank_name']; ?></a></td>
						<td align="left"><a href="<?php echo "/$c_name";?>/deposits/<?php echo $deposit_row['deposit_id']; ?>" class="credity_blue_link"><?php echo $deposit_row['name'];?></a></td>
						<td align="left"><?php
							echo "до ".number_format($deposit_row['percent'],2)." %";
						?></td>
					</tr><?php
				}
			?></table><?php
			require_once APP."pageskin.php";
		}
		else
			echo "<span class='gag'>Не найдено подходящего кредита</span>";
    ?></div><?php
}
?><div class="inside_block">
	<table width="100%" border="0" cellpadding="0" cellspacing="0">
		<tr valign='top'>
			<td width="344" class="inside_info"><?php
				require_once APP."bank_list.php";
				require_once APP."currency_rates.php";
			?></td>
			<td width="646"><?php
				$info = mysql_fetch_array(mysql_query("select * from `info` where `info_id` = '18' limit 1"));
				$text = getRichText($info['text']);
				echo "<h2>$info[header]</h2>";
				echo "<p>$text</p>";
			?></td>
		</tr>
	</table>
</div>
<?php require_once APP.FOOTERFILE; ?>